package com.ssy.lingxi.message.controller.inner;

import com.ssy.lingxi.common.controller.BaseController;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.message.api.vo.request.WsMessageRequest;
import com.ssy.lingxi.message.websocket.WsMessagePushService;
import com.ssy.lingxi.message.websocket.model.WsMessage;
import com.ssy.lingxi.message.websocket.session.WsSessionKey;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @menu 内部接口-websocket消息
 * @author yzc
 * @version 2.0.0
 * @date 2020/10/27
 */
@RestController
@RequestMapping("/message/wsMsg/feign")
public class WsMessageController extends BaseController {

    @Resource
    private WsMessagePushService wsMessagePushService;

    /**
     * 发送websocket消息
     * @param request 请求参数
     * @return 返回结果
     */
    @PostMapping("/send")
    public Wrapper<Void> sendWsMessage(@RequestBody WsMessageRequest request) {
        WsMessage wsMessage = WsMessage.builder()
                .action(request.getAction())
                .receiver(WsSessionKey.buildByMemberIdAndRoleId(request.getMemberId(), request.getRoleId()))
                .data(request.getData())
                .build();
        wsMessagePushService.pushMessage(wsMessage);
        return Wrapper.success();
    }

    /**
     * 发送websocket消息(批量)
     * @param request 请求参数
     * @return 返回结果
     */
    @PostMapping("/batchSend")
    public Wrapper<Void> batchSendWsMessage(@RequestBody List<WsMessageRequest> request) {
        List<WsMessage> wsMessageList = request.stream().map(e -> {
            return WsMessage.builder()
                    .action(e.getAction())
                    .receiver(WsSessionKey.buildByMemberIdAndRoleId(e.getMemberId(), e.getRoleId()))
                    .data(e.getData())
                    .build();
        }).collect(Collectors.toList());

        wsMessagePushService.pushMessageList(wsMessageList);
        return Wrapper.success();
    }
}
